package Day2025_01_22;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoServer {
    private ServerSocket socket;

    public TCPEchoServer(int port) throws IOException {
        if (port < 1025 || port > 65535) {
            throw new BindException("端口号必须在1025 ~ 65535之间.");
        }
        this.socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println(" 服务已启动, 等待客户端连接.");
        while (true) {
            Socket clientSocket = socket.accept();
            processConnections(clientSocket);
        }
    }

    private void processConnections(Socket clientSocket) {
        System.out.printf("[%s : %d] 客户端上线了.\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNextLine()) {
                    System.out.printf("[%s : %d] 客户端下线了.\n", clientSocket.getInetAddress().toString(), clientSocket.getPort());
                    break;
                }
                String request = scanner.nextLine();
                String response = process(request);
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s : %d] request = %s, response = %s.\n", clientSocket.getInetAddress().toString(), clientSocket.getPort(),
                        request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer server = new TCPEchoServer(9090);
        server.start();
    }
}
